package com.yupi.yangoj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yupi.yangoj.common.ErrorCode;
import com.yupi.yangoj.constant.CommonConstant;
import com.yupi.yangoj.exception.BusinessException;
import com.yupi.yangoj.judge.JudgeService;
import com.yupi.yangoj.model.dto.question.QuestionQueryRequest;
import com.yupi.yangoj.model.dto.questionsubmit.QuestionSubmitAddRequest;
import com.yupi.yangoj.model.dto.questionsubmit.QuestionSumitQueryRequest;
import com.yupi.yangoj.model.entity.Question;
import com.yupi.yangoj.model.entity.QuestionSubmit;
import com.yupi.yangoj.model.entity.User;
import com.yupi.yangoj.model.enums.QuestionSubmitStatusEnum;
import com.yupi.yangoj.model.enums.SystemLanguageEnum;
import com.yupi.yangoj.model.vo.QuestionSubmitVO;
import com.yupi.yangoj.model.vo.QuestionVO;
import com.yupi.yangoj.model.vo.UserVO;
import com.yupi.yangoj.service.QuestionService;
import com.yupi.yangoj.service.QuestionSubmitService;
import com.yupi.yangoj.mapper.QuestionSubmitMapper;
import com.yupi.yangoj.service.UserService;
import com.yupi.yangoj.utils.SqlUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.aop.framework.AopContext;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * @author Young
 * @description 针对表【question_submit(题目提交表)】的数据库操作Service实现
 * @createDate 2024-01-09 10:17:42
 */
@Service
public class QuestionSubmitServiceImpl extends ServiceImpl<QuestionSubmitMapper, QuestionSubmit>
        implements QuestionSubmitService {

    @Resource
    private QuestionService questionService;

    @Resource
    private UserService userService;

    @Resource
    @Lazy
    private JudgeService judgeService;

    /**
     * 用户提交题目
     *
     * @param questionSubmitAddRequest 提交的题目对象
     * @param loginUser                用户对象
     * @return 返回该题目提交数据的id
     */
    @Override
    public long doQuestionSubmit(QuestionSubmitAddRequest questionSubmitAddRequest, User loginUser) {
        //验证编程语言是否合法，是否为后端定义支持的语言枚举
        String language = questionSubmitAddRequest.getLanguage();
        SystemLanguageEnum enumByValue = SystemLanguageEnum.getEnumByValue(language);
        if (enumByValue == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "编程语言错误");
        }

        //判断题目是否存在
        Question question = questionService.getById(questionSubmitAddRequest.getQuestionId());
        if (question == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        //是否已提交题目(防止重复提交)
        Long userId = loginUser.getId();
//        //每个用户串行提交题目
//        //使用锁包裹事务
//        QuestionSubmitService questionSubmitService = (QuestionSubmitService) AopContext.currentProxy();
//        synchronized (String.valueOf(userId).intern()){
//            return questionSubmitService.doQuestionSubmitInner(userId,questionId);
//        }
        QuestionSubmit questionSubmit = new QuestionSubmit();
        questionSubmit.setUserId(userId);
        questionSubmit.setQuestionId(questionSubmitAddRequest.getQuestionId());
        questionSubmit.setCode(questionSubmitAddRequest.getCode());
        questionSubmit.setLanguage(language);
        //设置题目初始化提交状态
        questionSubmit.setStatus(QuestionSubmitStatusEnum.WAITING.getValue());
        questionSubmit.setJudgeInfo("{}");
        //插入数据库
        boolean save = this.save(questionSubmit);
        if (!save) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "数据插入失败");
        }
        //更改该题目的提交数+1
        question.setSubmitNum(question.getSubmitNum() + 1);
        boolean update = questionService.updateById(question);
        if (!update){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "题目提交数修改失败");
        }

        // 执行判题服务
        Long questionSubmitId = questionSubmit.getId();
        //异步地执行
        CompletableFuture.runAsync(() -> {
            judgeService.doSubmit(questionSubmitId);
        });

        //返回插入数据的id
        return questionSubmitId;
    }


    /**
     * 封装了事务的方法
     *
     * @param userId
     * @param questionId
     * @return
     */
    @Override
    public int doQuestionSubmitInner(Long userId, long questionId) {
        return 0;
    }


    /**
     * 获取查询包装类：根据前端传来的题目提交的查询条件字段，得到mybatis-plus的QueryWrapper条件查询（一个方法封装）
     *
     * @param questionSubmitQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<QuestionSubmit> getQueryWrapper(QuestionSumitQueryRequest questionSubmitQueryRequest) {
        QueryWrapper<QuestionSubmit> queryWrapper = new QueryWrapper<>();
        if (questionSubmitQueryRequest == null) {
            return queryWrapper;    //空的查询条件
        }
        String language = questionSubmitQueryRequest.getLanguage();
        Integer status = questionSubmitQueryRequest.getStatus();
        Long questionId = questionSubmitQueryRequest.getQuestionId();
        Long userId = questionSubmitQueryRequest.getUserId();
        String sortOrder = questionSubmitQueryRequest.getSortOrder();
        String sortField = questionSubmitQueryRequest.getSortField();

        // 拼接queryWrapper的查询条件并返回，提供给其他方法调用
        queryWrapper.eq(StringUtils.isNotBlank(language), "language", language);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(questionId), "questionId", questionId);
        queryWrapper.eq(QuestionSubmitStatusEnum.getEnumByValue(status) != null, "status", status);
        queryWrapper.orderByDesc("createTime");

        queryWrapper.eq("isDelete", false);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        //返回mp的查询条件
        return queryWrapper;
    }


    /**
     * 获取单个题目提交的VO对象
     *
     * @param questionSubmit
     * @param loginUser
     * @return
     */
    @Override
    public QuestionSubmitVO getQuestionSubmitVO(QuestionSubmit questionSubmit, User loginUser) {
        //将实体类对象转为vo对象
        QuestionSubmitVO questionSubmitVO = QuestionSubmitVO.objToVo(questionSubmit);
        //设置提交该题目的用户数据
        User byId = userService.getById(questionSubmit.getUserId());
        UserVO userVO = new UserVO();
        if (byId != null) {
            userVO.setId(byId.getId());
            userVO.setUserName(byId.getUserName());
            userVO.setUserAvatar(byId.getUserAvatar());
            userVO.setUserProfile(byId.getUserProfile());
            userVO.setUserRole(byId.getUserRole());
            userVO.setCreateTime(byId.getCreateTime());
        }
        questionSubmitVO.setUserVO(userVO);

        //脱敏：仅本人和管理员可以能够看见自己（提交userId与的登录用户的id是否相同）提交的代码
        Long userId = loginUser.getId();
        if (!Objects.equals(userId, questionSubmit.getUserId()) && !userService.isAdmin(loginUser)) {
            questionSubmitVO.setCode(null);
        }

        return questionSubmitVO;
    }


    /**
     * 获取单个题目提交的详情数据
     *
     * @param questionSubmit
     * @param loginUser
     * @return
     */
    @Override
    public QuestionSubmitVO getQuestionSubmitDetailVO(QuestionSubmit questionSubmit, User loginUser) {
        //将实体类对象转为vo对象
        QuestionSubmitVO questionSubmitVO = QuestionSubmitVO.objToVo(questionSubmit);
        //设置提交该题目的用户数据
        User byId = userService.getById(questionSubmit.getUserId());
        UserVO userVO = new UserVO();
        if (byId != null) {
            userVO.setId(byId.getId());
            userVO.setUserName(byId.getUserName());
            userVO.setUserAvatar(byId.getUserAvatar());
            userVO.setUserProfile(byId.getUserProfile());
            userVO.setUserRole(byId.getUserRole());
            userVO.setCreateTime(byId.getCreateTime());
        }
        questionSubmitVO.setUserVO(userVO);
        Question questionServiceById = questionService.getById(questionSubmit.getQuestionId());
        QuestionVO questionVO = QuestionVO.objToVo(questionServiceById);
        questionSubmitVO.setQuestionVO(questionVO);

        //脱敏：仅本人和管理员可以能够看见自己（提交userId与的登录用户的id是否相同）提交的代码（）
        Long userId = loginUser.getId();
        if (!Objects.equals(userId, questionSubmit.getUserId()) && !userService.isAdmin(loginUser)) {
            questionSubmitVO.setCode(null);
        }

        return questionSubmitVO;
    }

    /**
     * 分页题目提交VO对象
     *
     * @param questionSubmitPage
     * @param loginUser
     * @return
     */
    @Override
    public Page<QuestionSubmitVO> getQuestionSubmitVOPage(Page<QuestionSubmit> questionSubmitPage, User loginUser) {
        List<QuestionSubmit> questionSubmitList = questionSubmitPage.getRecords();
        Page<QuestionSubmitVO> questionSubmitVOPage = new Page<>(questionSubmitPage.getCurrent(), questionSubmitPage.getSize(), questionSubmitPage.getTotal());
        if (CollectionUtils.isEmpty(questionSubmitList)) {
            return questionSubmitVOPage;
        }
        //处理返回数据
        List<QuestionSubmitVO> questionSubmitVOList = questionSubmitList.stream()
                .map(questionSubmit -> getQuestionSubmitVO(questionSubmit, loginUser))
                .collect(Collectors.toList());
        questionSubmitVOPage.setRecords(questionSubmitVOList);
        //返回数据
        return questionSubmitVOPage;
    }


}




